/**
 * 此组件内的form暂无用处
 *
 * 如果后续添加设备类型配置、查询设备类型配置以及查询和修改设备配置的数据结构一致的话，才能用上form
 */

import deepClone from '@/libs/deepClone'
import { FormInstance } from 'ant-design-vue'
import { selectItemByCode, selectItemByTypeSign } from '@/api/information'
import CCard from '@/components/card'
import { CFormItem } from '@/components/form/form-item'
import {
  ParamSelect,
  NumMadeSelect,
  DataTypeSelect,
  ByteTypeSelect,
  ProductFileSelect
} from '@/components/select'
import { PropType } from 'vue'
import { CnBoldP, CnNormalSpan } from '../text'
import useEditModule from '@/hooks/useEditModule'
import useDevTypeConConfig from '@/hooks/deviceType/conConfig'

/**填写设备类型名称及备注 */
export const DeviceBaseInfoCard = defineComponent({
  props: {
    name: String,
    desc: String,
    collectRate: String,
    paramSwitch: String,
    title: String,
    isEdit: Boolean,
    submitBtnLoading: Boolean
  },
  emits: {
    'update:name': (val: string): Boolean => true,
    'update:desc': (val: string): Boolean => true,
    'update:collectRate': (val: string): Boolean => true,
    'update:paramSwitch': (val: string): Boolean => true,
    editSubmit: (): boolean => true,
    editeCancel: (): boolean => true
  },
  setup(props, { emit }) {
    const { moduleDisabled, openModule, closeModule } = useEditModule()

    function handleEditSubmit() {
      emit('editSubmit')
    }
    function handleEditCancel() {
      emit('editeCancel')
      closeModule()
    }

    onMounted(() => {
      if (props.isEdit === false) {
        openModule()
        console.log(moduleDisabled.value)
      }
    })
    return () => (
      <CCard
        class='rounded-6'
        titleType='inside'
        title={props.title ? props.title : '1.设备类型信息'}
        v-slots={
          props.isEdit
            ? {
                title: () => (
                  <div class='flex items-center justify-between space-x-12'>
                    <CnBoldP class='card-title hanzi text-14 text-xText'>
                      {props.title ? props.title : '1.设备类型信息'}
                    </CnBoldP>
                    {!moduleDisabled.value ? (
                      <a-button size='small' onClick={openModule}>
                        修改
                      </a-button>
                    ) : (
                      <div class='flex items-center space-x-12'>
                        <a-button size='small' onClick={handleEditCancel}>
                          取消
                        </a-button>
                        ,
                        <a-button
                          loading={props.submitBtnLoading}
                          type='primary'
                          size='small'
                          onClick={handleEditSubmit}
                        >
                          提交
                        </a-button>
                      </div>
                    )}
                  </div>
                )
              }
            : null
        }
      >
        <div class='pt-16'>
          <CFormItem label='设备类型' name='devTypeName'>
            <a-input
              value={props.name}
              onInput={(e: { target: { value: string } }) => {
                emit('update:name', e.target.value)
              }}
              disabled={props.isEdit}
            ></a-input>
          </CFormItem>

          {props.isEdit
            ? [
                <CFormItem label='采集频率'>
                  <a-input
                    type='number'
                    value={props.collectRate}
                    onInput={(e: { target: { value: string } }) => {
                      emit('update:collectRate', e.target.value)
                    }}
                    disabled={!moduleDisabled.value}
                  ></a-input>
                </CFormItem>,
                <CFormItem label='数据开关'>
                  <a-switch
                    checked={props.paramSwitch}
                    disabled={!moduleDisabled.value}
                    checkedValue='1'
                    checkedChildren='已开启'
                    unCheckedValue='2'
                    unCheckedChildren='已关闭'
                    onChange={(checked: any) => {
                      console.log(checked)
                      emit('update:paramSwitch', checked)
                    }}
                  />
                </CFormItem>
              ]
            : null}

          <CFormItem label='备注' name='devTypeDesc'>
            <a-input
              value={props.desc}
              onInput={(e: { target: { value: string } }) => {
                emit('update:desc', e.target.value)
              }}
              disabled={!moduleDisabled.value}
            ></a-input>
          </CFormItem>
        </div>
      </CCard>
    )
  }
})
/**选择设备类型信息 */
export const DeviceBaseDatasCard = defineComponent({
  props: {
    baseDatas: {
      type: Array as PropType<AddDevType.DevTypeBaseData[]>
    },

    title: String,
    isEdit: Boolean,
    submitBtnLoading: Boolean
  },
  emits: {
    'update:baseDatas': (val: AddDevType.DevTypeBaseData[]): Boolean => true,
    editSubmit: (): boolean => true,
    editeCancel: (): boolean => true
  },
  setup(props, { emit }) {
    let state = reactive<{
      options: SysDict.Item[]
      checkedList: string[]
      baseDatas: AddDevType.DevTypeBaseData[]
    }>({
      options: [],
      checkedList: [],
      baseDatas: []
    })

    const checkboxList = computed(() => {
      if (state.options.length) {
        return state.options.map(item => ({ label: item.dictName, value: item.dictCode }))
      } else if (props.baseDatas && props.baseDatas.length) {
        return props.baseDatas.map(item => ({
          label: item.devTypeBaseDataName,
          value: item.devTypeBaseDataCode
        }))
      } else {
        return []
      }
    })

    watch(
      () => props.baseDatas,
      n => {
        if (n) {
          let checkedList = n
            .filter(item => item.status === '1')
            .map(item => item.devTypeBaseDataCode)

          for (let index = 0; index < checkedList.length; index++) {
            const code = checkedList[index]
            if (!state.checkedList.includes(code)) {
              state.checkedList = checkedList
              break
            }
          }
        } else {
          state.checkedList = []
        }
      },
      { immediate: true }
    )

    watch(
      () => state.checkedList,
      n => {
        console.log(n)

        if (props.baseDatas?.length) {
          let baseDatas: AddDevType.DevTypeBaseData[] = deepClone(
            props.baseDatas
          ) as AddDevType.DevTypeBaseData[]

          for (let i = 0; i < n.length; i++) {
            const code = n[i]
            let baseData = baseDatas.find(item => item.devTypeBaseDataCode === code)
            if (baseData) {
              baseData.status = '1'
            }
          }
          emit('update:baseDatas', baseDatas)
        }
      }
    )

    const getOptions = () => {
      selectItemByTypeSign({ dataType: 'devTypeMsgs' })
        .then(res => {
          state.options = res.data
          if (props.isEdit === false) {
            let baseDatas: AddDevType.DevTypeBaseData[] = res.data.map<AddDevType.DevTypeBaseData>(
              item => {
                return {
                  devTypeBaseDataId: -1,
                  devTypeBaseDataName: item.dictName,
                  devTypeId: -1,
                  devTypeBaseDataCode: item.dictCode,
                  status: '0'
                }
              }
            )
            emit('update:baseDatas', baseDatas)
          }
        })
        .catch(err => {
          state.options = []
          if (props.isEdit === false) {
            emit('update:baseDatas', [])
          }
        })
    }

    function handleChange(e: string[]) {
      console.log(e)

      if (state.options.length) {
        let baseDataList = state.options.map<AddDevType.DevTypeBaseData>(option => {
          let status: '0' | '1' = e.find(code => option.dictCode === code) ? '1' : '0'
          return {
            devTypeBaseDataName: option.dictName,
            devTypeBaseDataId: -1,
            devTypeId: -1,
            devTypeBaseDataCode: option.dictCode,
            status: status
          }
        })
        console.log(baseDataList)

        emit('update:baseDatas', baseDataList)
      } else if (props.baseDatas && props.baseDatas.length) {
        let baseDataList = deepClone(props.baseDatas) as typeof props.baseDatas
        for (let j = 0; j < baseDataList.length; j++) {
          const baseData = baseDataList[j]
          let status: '0' | '1' = e.includes(baseData.devTypeBaseDataCode) ? '1' : '0'
          baseData.status = status
        }
        console.log(baseDataList)
        emit('update:baseDatas', baseDataList)
      } else {
        console.log([])
        emit('update:baseDatas', [])
      }
    }

    const { moduleDisabled, openModule, closeModule } = useEditModule()
    function handleEditSubmit() {
      emit('editSubmit')
    }
    function handleEditCancel() {
      emit('editeCancel')
      closeModule()
    }

    onMounted(() => {
      if (props.isEdit === false) {
        openModule()
        getOptions()
        handleChange([])
      }
    })

    return () => (
      <CCard
        class='rounded-6'
        titleType='inside'
        title={props.title ? props.title : '2.基础信息'}
        v-slots={
          props.isEdit
            ? {
                title: () => (
                  <div class='flex items-center justify-between space-x-12'>
                    <CnBoldP class='card-title hanzi text-14 text-xText'>
                      {props.title ? props.title : '2.基础信息'}
                    </CnBoldP>
                    {!moduleDisabled.value ? (
                      <a-button size='small' onClick={openModule}>
                        修改
                      </a-button>
                    ) : (
                      <div class='flex items-center space-x-12'>
                        <a-button size='small' onClick={handleEditCancel}>
                          取消
                        </a-button>
                        ,
                        <a-button
                          loading={props.submitBtnLoading}
                          type='primary'
                          size='small'
                          onClick={handleEditSubmit}
                        >
                          提交
                        </a-button>
                      </div>
                    )}
                  </div>
                )
              }
            : null
        }
      >
        <CFormItem class='mb-0' showLabel={false} name='devTypeBaseDataList'>
          <a-checkbox-group
            v-model={[state.checkedList, 'value']}
            disabled={!moduleDisabled.value}
            onChange={handleChange}
          >
            {checkboxList.value.map(item => (
              <a-checkbox class='m-2' value={item.value}>
                {item.label}
              </a-checkbox>
            ))}
          </a-checkbox-group>
        </CFormItem>
      </CCard>
    )
  }
})

/**选择设备类型的功能 */
export const DeviceFunSignsCard = defineComponent({
  props: {
    value: {
      type: Object as PropType<AddDevType.DevTypeFunSign>
    },

    option: Object as PropType<AddDevType.DevTypeFunSign>,

    title: String,

    isEdit: Boolean,
    submitBtnLoading: Boolean
  },
  emits: {
    'update:value': (val: AddDevType.DevTypeFunSign): Boolean => true,
    editSubmit: (): boolean => true,
    editeCancel: (): boolean => true
  },
  setup(props, { emit }) {
    let state = reactive<{
      options: SysDict.Item[]
      data: AddDevType.DevTypeFunSign
      codeList: string[]
    }>({
      options: [],
      data: {},
      codeList: []
    })

    const checkedOptions = computed(() =>
      state.options.filter(item => state.codeList.includes(item.dictCode))
    )

    watch(
      () => props.value,
      n => {
        if (n && Object.keys(n).length) {
          console.log('设备功能列表 父组件传值 有值', n)
          let checkedList = Object.values(n)
            .filter(item => item.status === '1')
            .map((val: AddDevType.DevTypeFunSignData) => val.code)

          state.codeList = checkedList
        } else {
          console.log('设备功能列表 父组件传值 无值', n)
          state.codeList = []
        }
      },
      { deep: true, immediate: true }
    )

    watch(
      () => state.codeList,
      n => {
        console.log('设备类型功能被选择', n, state.data)
        // let dataClone = deepClone(state.data) as typeof state.data
        Object.keys(state.data || {}).forEach(key => {
          let code = state.data?.[key].code
          if (code && n.includes(code)) {
            if (state.data && state.data[key]) {
              state.data[key].status = '1'
            }
          } else {
            if (state.data && state.data[key]) {
              state.data[key].status = '0'
              state.data[key].value = ''
            }
          }
        })
      },
      { deep: true, immediate: true }
    )

    watch(
      () => state.data,
      n => {
        emit('update:value', n)
      },
      { deep: true, immediate: true }
    )

    const { moduleDisabled, openModule, closeModule } = useEditModule()
    function handleEditSubmit() {
      emit('editSubmit')
    }
    function handleEditCancel() {
      emit('editeCancel')
      closeModule()
    }

    const getOptions = () => {
      selectItemByTypeSign({ dataType: 'devTypeFuns' })
        .then(res => {
          state.options = res.data
          // 根据返回的设备功能列表，处理成 AddDevType.DevTypeFunSign 类型的对象
          // 给组件state.data赋值
          // 同时返回value给父组件
          let value: AddDevType.DevTypeFunSign = {}
          res.data.forEach(item => {
            value[item.dictValue] = {
              value: '',
              code: item.dictCode,
              status: '0'
            }
          })
          state.data = value
        })
        .catch(err => {})
    }

    onMounted(() => {
      getOptions()
    })

    return () => (
      <CCard
        class='rounded-6'
        titleType='inside'
        title={props.title ? props.title : '3.选择功能'}
        v-slots={
          props.isEdit
            ? {
                title: () => (
                  <div class='flex items-center justify-between space-x-12'>
                    <CnBoldP class='card-title hanzi text-14 text-xText'>
                      {props.title ? props.title : '3.选择功能'}
                    </CnBoldP>
                    {!moduleDisabled.value ? (
                      <a-button size='small' onClick={openModule}>
                        修改
                      </a-button>
                    ) : (
                      <div class='flex items-center space-x-12'>
                        <a-button size='small' onClick={handleEditCancel}>
                          取消
                        </a-button>
                        ,
                        <a-button
                          loading={props.submitBtnLoading}
                          type='primary'
                          size='small'
                          onClick={handleEditSubmit}
                        >
                          提交
                        </a-button>
                      </div>
                    )}
                  </div>
                )
              }
            : null
        }
      >
        <div class='pt-20'>
          <CFormItem class='mb-0' showLabel={false} name='devTypeBaseDataList'>
            <a-checkbox-group
              v-model={[state.codeList, 'value']}
              disabled={props.isEdit && !moduleDisabled.value}
              onChange={(checkedList: string[]) => {
                state.codeList = checkedList
              }}
            >
              {state.options.map(item => (
                <a-checkbox class='m-2' value={item.dictCode}>
                  {item.dictName}
                </a-checkbox>
              ))}
            </a-checkbox-group>
          </CFormItem>
          <div class='w-full flex flex-wrap justify-start gap-x-12 gap-y-8'>
            {Object.keys(state.data || {}).map(key => {
              let currentOption = checkedOptions.value.filter(option => option.dictValue === key)[0]

              if (currentOption && state.data && state.data?.[key])
                return (
                  <CCard
                    class='rounded-6 my-4 shadow-none'
                    titleType='inside'
                    title={currentOption.dictName}
                    isMain={false}
                  >
                    <CFormItem class='mb-0' label='内容'>
                      <a-input
                        class='ml-8'
                        disabled={props.isEdit && !moduleDisabled.value}
                        v-model={[state.data[key].value, 'value']}
                        placeholder=''
                      ></a-input>
                    </CFormItem>
                  </CCard>
                )
            })}
          </div>
        </div>
      </CCard>
    )
  }
})
/**JSON协议配置组件 */
export const TxconfForJSON = defineComponent({
  props: {
    txConf: {
      type: Object as PropType<AddDevType.TxConf_JSON>
    },
    disabled: Boolean,
    isEdit: Boolean
  },
  emits: {
    'update:txConf': (val: AddDevType.TxConf_JSON): Boolean => true,
    confChange: (val: AddDevType.TxConf_JSON): Boolean => true
  },
  setup(props, { emit }) {
    console.log(props.txConf)

    let state = reactive<{ confData: AddDevType.TxConf_JSON | undefined }>({
      confData: undefined
    })

    watch(
      () => props.txConf,
      n => {
        console.log('JSON协议配置 父组件传值 变化', n)
        if (n) {
          state.confData = n
        }
      },
      { deep: true, immediate: true }
    )

    watch(
      () => state.confData,
      n => {
        console.log('JSON协议配置 变化', n)
        if (n !== undefined) {
          emit('confChange', n)
          emit('update:txConf', n)
        }
      },
      { deep: true }
    )

    const handleAddParam = () => {
      state.confData?.paramConfDataList.push({
        sort: `${state.confData.paramConfDataList.length}`,
        paramCode: '',
        reserveNum: '',
        confId: undefined,
        confDataId: undefined,
        paramName: '',
        paramDesc: undefined
      })
    }

    const handleDeleteParam = (idx: number) => {
      state.confData?.paramConfDataList.splice(idx, 1)
    }

    onMounted(() => {
      console.log(props.disabled)
    })
    return () => (
      <CCard
        class='rounded-6 my-4 shadow-none'
        titleType='inside'
        title='JSON协议配置'
        isMain={false}
      >
        {{
          title: () => (
            <div>
              {state.confData ? (
                <a-switch
                  v-model={[state.confData.jdtParamConfFlag, 'checked']}
                  disabled={props.disabled}
                  checkedValue='1'
                  checkedChildren='固定参数'
                  unCheckedValue='2'
                  unCheckedChildren='非固定参数'
                  onChange={(checked: any) => {
                    console.log(checked)
                  }}
                />
              ) : null}

              {state.confData && state.confData.jdtParamConfFlag === '1' ? (
                <a-button
                  class='ml-16'
                  type='primary'
                  size='small'
                  disabled={props.disabled}
                  onClick={handleAddParam}
                >
                  添加参数
                </a-button>
              ) : null}
            </div>
          ),
          default: () => (
            <div class='flex flex-col gap-y-8 pt-16'>
              {state.confData &&
                state.confData.paramConfDataList.map((param, idx) => (
                  <div class='w-full flex justify-start items-center flex-nowrap mb-2 space-x-4'>
                    <div class='flex items-center space-x-4'>
                      <CnNormalSpan>参数:</CnNormalSpan>
                      <ParamSelect
                        class='w-160'
                        v-model={[
                          (state.confData as AddDevType.TxConf_JSON).paramConfDataList[idx]
                            .paramCode,
                          'code'
                        ]}
                        disabled={props.disabled}
                      ></ParamSelect>
                    </div>
                    <div class='flex items-center space-x-4'>
                      <CnNormalSpan>保留位数:</CnNormalSpan>
                      <a-input
                        class='flex-1'
                        type='number'
                        v-model={[
                          (state.confData as AddDevType.TxConf_JSON).paramConfDataList[idx]
                            .reserveNum,
                          'value'
                        ]}
                        disabled={props.disabled}
                        placeholder='保留位数'
                      ></a-input>
                    </div>
                    <div class='flex items-center space-x-4'>
                      <CnNormalSpan>备注:</CnNormalSpan>
                      <a-input
                        class='flex-1'
                        v-model={[
                          (state.confData as AddDevType.TxConf_JSON).paramConfDataList[idx]
                            .paramDesc,
                          'value'
                        ]}
                        disabled={props.disabled}
                        placeholder='备注'
                      ></a-input>
                    </div>

                    <a-button
                      size='small'
                      type='danger'
                      disabled={props.disabled}
                      onClick={() => handleDeleteParam(idx)}
                    >
                      删除
                    </a-button>
                  </div>
                ))}
            </div>
          )
        }}
      </CCard>
    )
  }
})
/**MODBUS协议配置组件 */
export const TxconfForMODBUS = defineComponent({
  props: {
    txConf: Array as PropType<AddDevType.TxConf_MODBUS[]>,
    disabled: Boolean,
    isEdit: Boolean
  },
  emits: {
    confChange: (val: AddDevType.TxConf_MODBUS[]): Boolean => true
  },
  setup(props, { emit }) {
    console.log(props.txConf)

    let state = reactive<{ confDatas: AddDevType.TxConf_MODBUS[] }>({
      confDatas: []
    })
    watch(
      () => props.txConf,
      n => {
        console.log('MODBUS协议配置 父组件传值 变化', n)
        if (Array.isArray(n) && n.length) {
          state.confDatas = n
        }
      },
      { deep: true, immediate: true }
    )

    watch(
      () => state.confDatas,
      n => {
        console.log('MODBUS协议配置 变化', n)
        emit('confChange', n)
      },
      { deep: true }
    )

    const handleAddConfData = () => {
      state.confDatas.push({
        addressCode: '',
        funCode: '',
        sort: `${state.confDatas.length}`,
        paramConfDataList: [],
        confId: undefined,
        devTypeId: undefined,
        mdtParamConfDesc: ''
      })
    }

    const handleDeleteConfData = (idx: number) => {
      if (state.confDatas !== undefined) {
        state.confDatas.splice(idx, 1)
      }
    }

    const handleAddConfDataParam = (confDataIdx: number) => {
      state.confDatas[confDataIdx].paramConfDataList.push({
        sort: `${state.confDatas[confDataIdx].paramConfDataList.length}`,
        paramCode: '',
        numMade: 0,
        startHexStr: '',
        byteType: 'BB',
        dataType: 'INT',
        reserveNum: '',

        confId: undefined,
        confDataId: undefined,
        paramName: '',
        paramDesc: undefined
      })
    }

    const handleDeleteConfDataParam = (confDataIdx: number, paramIdx: number) => {
      if (state.confDatas !== undefined) {
        state.confDatas[confDataIdx].paramConfDataList.splice(paramIdx, 1)
      }
    }

    onMounted(() => {})

    return () => (
      <CCard
        class='rounded-6 my-4 shadow-none px-0'
        titleType='inside'
        title='MODBUS协议配置'
        isMain={false}
      >
        {{
          title: () => (
            <div>
              <a-button
                class='mx-4'
                type='primary'
                size='small'
                disabled={props.disabled}
                onClick={handleAddConfData}
              >
                添加参数集
              </a-button>
            </div>
          ),
          default: () =>
            state.confDatas &&
            state.confDatas.map((confData, confDataIdx) => (
              <CCard class='rounded-6 my-8' titleType='inside' title='参数集' isMain={false}>
                {{
                  title: () => (
                    <div>
                      <a-button
                        class='mx-4'
                        type='danger'
                        size='small'
                        disabled={props.disabled}
                        onClick={() => handleDeleteConfData(confDataIdx)}
                      >
                        删除该参数集
                      </a-button>
                      <a-button
                        class='mx-4'
                        type='primary'
                        size='small'
                        disabled={props.disabled}
                        onClick={() => handleAddConfDataParam(confDataIdx)}
                      >
                        添加参数
                      </a-button>
                    </div>
                  ),
                  default: () =>
                    state.confDatas ? (
                      <div class='pt-16'>
                        <CFormItem label='485地址'>
                          <a-input
                            v-model={[state.confDatas[confDataIdx].addressCode, 'value']}
                            disabled={props.disabled}
                            placeholder='输入485地址'
                          ></a-input>
                        </CFormItem>
                        <CFormItem label='功能码'>
                          <a-input
                            v-model={[state.confDatas[confDataIdx].funCode, 'value']}
                            disabled={props.disabled}
                            placeholder='输入功能码'
                          ></a-input>
                        </CFormItem>
                        <div class='space-y-24'>
                          {confData.paramConfDataList.map((paramData, paramDataIdx) =>
                            state.confDatas ? (
                              <div class='w-220 inline-block space-y-12 px-8'>
                                <div class='inline-grid grid-cols-3 gap-y-8 gap-x-8'>
                                  <div class='flex flex-col space-y-8 text-right'>
                                    <span class='inline-block h-32 leading-32 '>参数:</span>
                                    <span class='inline-block h-32 leading-32 '>起始位:</span>
                                    <span class='inline-block h-32 leading-32 '>数据类型:</span>
                                    <span class='inline-block h-32 leading-32 '>操作位:</span>
                                    <span class='inline-block h-32 leading-32 '>保留位数:</span>
                                    <span class='inline-block h-32 leading-32 '>字节序:</span>
                                    <span class='inline-block h-32 leading-32 '>备注:</span>
                                  </div>
                                  <div class='col-span-2 flex flex-col space-y-8'>
                                    {/* 选择参数 */}
                                    <ParamSelect
                                      class='h-32'
                                      v-models={[
                                        [
                                          state.confDatas[confDataIdx].paramConfDataList[
                                            paramDataIdx
                                          ].paramCode,
                                          'code'
                                        ],
                                        [
                                          state.confDatas[confDataIdx].paramConfDataList[
                                            paramDataIdx
                                          ].paramName,
                                          'name'
                                        ]
                                      ]}
                                      disabled={props.disabled}
                                    ></ParamSelect>
                                    {/* 起始位 */}
                                    <a-input
                                      class='h-32'
                                      v-model={[
                                        state.confDatas[confDataIdx].paramConfDataList[paramDataIdx]
                                          .startHexStr,
                                        'value'
                                      ]}
                                      disabled={props.disabled}
                                      placeholder='起始位(Hex)'
                                    ></a-input>
                                    {/* 数据类型 */}
                                    <DataTypeSelect
                                      class='h-32'
                                      v-model={[
                                        state.confDatas[confDataIdx].paramConfDataList[paramDataIdx]
                                          .dataType,
                                        'code'
                                      ]}
                                      disabled={props.disabled}
                                    ></DataTypeSelect>
                                    {/* 操作位 */}
                                    <NumMadeSelect
                                      class='h-32'
                                      v-model={[
                                        state.confDatas[confDataIdx].paramConfDataList[paramDataIdx]
                                          .numMade,
                                        'code'
                                      ]}
                                      disabled={props.disabled}
                                    ></NumMadeSelect>
                                    {/* 保留位数 */}
                                    <a-input
                                      class='h-32'
                                      type='number'
                                      v-model={[
                                        state.confDatas[confDataIdx].paramConfDataList[paramDataIdx]
                                          .reserveNum,
                                        'value'
                                      ]}
                                      disabled={props.disabled}
                                      placeholder='保留位数'
                                    ></a-input>
                                    {/* 字节序 */}
                                    <ByteTypeSelect
                                      class='h-32'
                                      v-model={[
                                        state.confDatas[confDataIdx].paramConfDataList[paramDataIdx]
                                          .byteType,
                                        'code'
                                      ]}
                                      disabled={props.disabled}
                                    ></ByteTypeSelect>
                                    {/* 备注 */}
                                    <a-input
                                      class='h-32'
                                      v-model={[
                                        state.confDatas[confDataIdx].paramConfDataList[paramDataIdx]
                                          .paramDesc,
                                        'value'
                                      ]}
                                      disabled={props.disabled}
                                      placeholder='填写备注'
                                    ></a-input>
                                  </div>
                                </div>
                                <div class='flex items-center justify-center'>
                                  <a-button
                                    class='w-full h-32'
                                    size='small'
                                    type='danger'
                                    disabled={props.disabled}
                                    onClick={() =>
                                      handleDeleteConfDataParam(confDataIdx, paramDataIdx)
                                    }
                                  >
                                    删除
                                  </a-button>
                                </div>
                              </div>
                            ) : null
                          )}
                        </div>
                      </div>
                    ) : null
                }}
              </CCard>
            ))
        }}
      </CCard>
    )
  }
})
/**通信配置 */
export const DeviceConConfigCard = defineComponent({
  props: {
    dataType: String as PropType<DevTypeDataType>,
    txConf: Object as PropType<AddDevType.TxConf>,
    txType: {
      type: String as PropType<DevTypeTxType>
    },
    heart: {
      type: String as PropType<DevTypeHeart>
    },
    title: {
      type: String,
      default: '4.通信配置'
    },
    isEdit: Boolean,
    submitBtnLoading: Boolean
  },
  emits: {
    'update:txType': (val: DevTypeTxType): boolean => true,
    'update:heart': (val: DevTypeHeart): boolean => true,
    'update:dataType': (val: DevTypeDataType): Boolean => true,
    'update:txConf': (val: AddDevType.TxConf): Boolean => true,
    editSubmit: (): boolean => true,
    editeCancel: (): boolean => true
  },
  setup(props, { emit }) {
    const { moduleDisabled, openModule, closeModule } = useEditModule()

    const {
      devTypeTxTypeList,
      updateDevTypeTxTypeList,
      devTypeDataTypeList,
      updateDevTypeDataTypeList
    } = useDevTypeConConfig()

    function handleEditSubmit() {
      emit('editSubmit')
    }
    function handleEditCancel() {
      emit('editeCancel')
      closeModule()
    }

    onMounted(() => {
      updateDevTypeTxTypeList()
      updateDevTypeDataTypeList()
      if (props.isEdit === false) {
        openModule()
        console.log(moduleDisabled.value)
      }
    })

    return () => (
      <CCard
        class='rounded-6'
        titleType='inside'
        title={props.title ? props.title : '4.通信配置'}
        v-slots={
          props.isEdit
            ? {
                title: () => (
                  <div class='flex items-center justify-between space-x-12'>
                    <CnBoldP class='card-title hanzi text-14 text-xText'>
                      {props.title ? props.title : '4.通信配置'}
                    </CnBoldP>
                    {!moduleDisabled.value ? (
                      <a-button size='small' onClick={openModule}>
                        修改
                      </a-button>
                    ) : (
                      <div class='flex items-center space-x-12'>
                        <a-button size='small' onClick={handleEditCancel}>
                          取消
                        </a-button>
                        ,
                        <a-button
                          loading={props.submitBtnLoading}
                          type='primary'
                          size='small'
                          onClick={handleEditSubmit}
                        >
                          提交
                        </a-button>
                      </div>
                    )}
                  </div>
                )
              }
            : null
        }
      >
        <div class='pt-20'>
          {props.isEdit
            ? null
            : [
                <CFormItem label='通信类型' name='devTypeConConfigSign.devTypeTxTypeCode'>
                  <a-radio-group
                    value={props.txType}
                    name='devTypeTxTypeCode'
                    disabled={!moduleDisabled.value}
                    onChange={(e: { target: { value: DevTypeTxType } }) => {
                      emit('update:txType', e.target.value)
                    }}
                  >
                    {devTypeTxTypeList.value.map(item => (
                      <a-radio class='m-2' value={item.dictCode} name='devTypeTxTypeCode'>
                        {item.dictName}
                      </a-radio>
                    ))}
                  </a-radio-group>
                </CFormItem>,
                <>
                  {props.txType === '0018' ? (
                    <CFormItem label='心跳包' name='devTypeConConfigSign.devTypeHeart'>
                      <a-input
                        value={props.heart}
                        disabled={!moduleDisabled.value}
                        onInput={(e: { target: { value: string } }) => {
                          emit('update:heart', e.target.value)
                        }}
                      ></a-input>
                    </CFormItem>
                  ) : null}
                </>,

                <CFormItem label='通信协议类型' name='devTypeConConfigSign.devTypeTxTypeCode'>
                  <a-radio-group
                    value={props.dataType}
                    name='devTypeTxTypeCode'
                    disabled={!moduleDisabled.value}
                    onChange={(e: { target: { value: DevTypeDataType } }) => {
                      emit('update:dataType', e.target.value)
                    }}
                  >
                    {devTypeDataTypeList.value.map(item => (
                      <a-radio class='m-2' value={item.dictCode} name='devTypeTxTypeCode'>
                        {item.dictName}
                      </a-radio>
                    ))}
                  </a-radio-group>
                </CFormItem>
              ]}

          {props.dataType === '0019' ? (
            <TxconfForJSON
              txConf={props.txConf as AddDevType.TxConf_JSON}
              disabled={!moduleDisabled.value}
              onConfChange={conf => emit('update:txConf', conf)}
              isEdit={props.isEdit}
            ></TxconfForJSON>
          ) : (
            <TxconfForMODBUS
              txConf={props.txConf as AddDevType.TxConf_MODBUS[]}
              disabled={!moduleDisabled.value}
              onConfChange={conf => emit('update:txConf', conf)}
              isEdit={props.isEdit}
            ></TxconfForMODBUS>
          )}
        </div>
      </CCard>
    )
  }
})

/**选择产品资料 */
export const DeviceProductsCard = defineComponent({
  props: {
    value: Array as PropType<AddDevType.DevTypeProductFileList>,
    title: String
  },
  emits: {
    fileChange: (val: AddDevType.DevTypeProductFileList): Boolean => true
  },
  setup(props, { emit }) {
    let state = reactive<{
      instruction: AddDevType.DevTypeProductFileListData
      operateVideo: AddDevType.DevTypeProductFileListData
      fileList: AddDevType.DevTypeProductFileList
      instructions: AddDevType.DevTypeProductFileList
      operateVideos: AddDevType.DevTypeProductFileList
      fileTypeList: SysDict.Item[]
      checkFileList: AddDevType.DevTypeProductFileList[]
      canUpdate: boolean
    }>({
      instruction: {
        devTypePFTypeCode: '0045',
        devTypePFDesc: '',
        devTypePFUrl: '',
        devTypePFPath: '',
        devTypePFName: ''
      },
      operateVideo: {
        devTypePFTypeCode: '0046',
        devTypePFDesc: '',
        devTypePFUrl: '',
        devTypePFPath: '',
        devTypePFName: ''
      },
      instructions: [],
      operateVideos: [],
      checkFileList: [],
      fileTypeList: [],
      fileList: [],
      canUpdate: true
    })

    watch(
      () => props.value,
      n => {
        console.log('6.选择产品资料', n)

        if (n && n.length) {
          n.forEach(item => {
            if (item.devTypePFTypeCode === '0045') {
              state.instruction.devTypePFUrl = item.devTypePFUrl
              state.instruction.devTypePFDesc = item.devTypePFDesc
            } else if (item.devTypePFTypeCode === '0046') {
              state.operateVideo.devTypePFUrl = item.devTypePFUrl
              state.operateVideo.devTypePFDesc = item.devTypePFDesc
            }
          })
        } else {
          state.instruction.devTypePFUrl = ''
          state.instruction.devTypePFDesc = ''
          state.operateVideo.devTypePFUrl = ''
          state.operateVideo.devTypePFDesc = ''
        }
      },
      { deep: true }
    )

    watch(
      () => state.fileList,
      n => {
        console.log('监听 文件列表', n, '是否可更新？' + state.canUpdate)
        state.canUpdate && emit('fileChange', n)
      },
      { deep: true }
    )
    watch(
      () => [...state.checkFileList],
      (n, o) => {
        console.log('监听 被选择的文件列表', n, o)
        state.canUpdate = false
        for (let i = 0; i < n.length; i++) {
          const nVal = n[i]
          const oVal = o[i]
          if (!oVal) {
            nVal.forEach(item => fileListAdd(item))
            continue
          }
          if (nVal.length > oVal.length) {
            nVal.forEach(item => {
              !oVal.includes(item) && fileListAdd(item)
            })
          } else {
            oVal.forEach(item => {
              !nVal.includes(item) && fileListDelete(item)
            })
          }
        }

        state.canUpdate = true
      },
      { deep: true }
    )

    const fileListAdd = (val: AddDevType.DevTypeProductFileListData) => {
      let idx = state.fileList.findIndex(item => item.devTypePFName === val.devTypePFName)
      if (idx === -1) {
        console.log('不存在相同数据，添加进fileList')
        state.fileList.push(val)
      } else {
        console.log('存在相同文件，替换对应下标的数据')
        state.fileList[idx] = val
      }
    }

    const fileListDelete = (val: AddDevType.DevTypeProductFileListData) => {
      let idx = state.fileList.findIndex(item => item.devTypePFName === val.devTypePFName)
      if (idx !== -1) {
        console.log('存在需要删除的数据，开始删除')
        state.fileList.splice(idx, 1)
      }
    }

    onMounted(async () => {
      let res = await selectItemByCode({ code: '0047' }).catch(err => {})
      if (res) {
        state.fileTypeList = res.data
        state.checkFileList = new Array(res.data.length).fill(1).map(item => [])
        console.log(state.checkFileList)
      }
    })

    return () => (
      <CCard
        class='rounded-6 my-8'
        titleType='inside'
        title={props.title ? props.title : '6.选择产品资料'}
      >
        {state.fileTypeList.map((fileType, idx) => (
          <a-form-item
            class='flex items-center gap-x-8'
            label={fileType.dictName}
            name={fileType.dictName}
          >
            <ProductFileSelect
              mode='multiple'
              fileType={fileType.dictCode}
              onSelectChange={e => {
                if (Array.isArray(e)) {
                  state.checkFileList[idx] = e.map(item => ({
                    devTypePFTypeCode: item.fileTypeCode,
                    devTypePFDesc: '',
                    devTypePFUrl: item.fileUrl,
                    devTypePFPath: item.filePath,
                    devTypePFName: item.fileName
                  }))
                }
              }}
            ></ProductFileSelect>
          </a-form-item>
        ))}
      </CCard>
    )
  }
})

const DeviceConfigInfo = defineComponent({
  name: 'deviceConfigInfo',
  props: {
    /**类型名称 */
    devTypeName: String,

    /**类型备注 */
    devTypeDesc: String,

    /**设备类型信息栏中被勾选的选项 */
    devTypeBaseDataList: Object as PropType<AddDevType.DevTypeBaseData>,

    /**传输协议配置 */
    devTypeConConfigSign: Object as PropType<AddDevType.DevTypeConConfigSign>,

    /**设备功能 */
    devTypeFunSign: Object as PropType<AddDevType.DevTypeFunSign>,

    /**设备资料 */
    devTypeProductFileList: Object as PropType<AddDevType.DevTypeProductFileList>,

    showFirst: {
      type: Boolean,
      default: true
    },
    firstTitle: String,
    showSecond: {
      type: Boolean,
      default: true
    },
    secondTitle: String,
    showThird: {
      type: Boolean,
      default: true
    },
    thirdTitle: String,
    showFourth: {
      type: Boolean,
      default: true
    },
    fourthTitle: String,
    showFifth: {
      type: Boolean,
      default: true
    },
    fifthTitle: String,
    showSixth: {
      type: Boolean,
      default: true
    },
    sixthTitle: String
  },
  emits: {
    submit: (data: AddDevType.Form): boolean => true,
    'update:devTypeName': (data: string): boolean => true,
    'update:devTypeDesc': (data: string): boolean => true,

    'update:devTypeBaseDataList': (data: AddDevType.DevTypeBaseData): boolean => true,

    'update:devTypeConConfigSign': (data: AddDevType.DevTypeConConfigSign): boolean => true,

    'update:devTypeFunSign': (data: AddDevType.DevTypeFunSign): boolean => true,

    'update:devTypeProductFileList': (data: AddDevType.DevTypeProductFileList): boolean => true
  },
  setup(props, { emit }) {
    let formRef = ref<FormInstance>()
    let loading = ref(false)
    const data_source = reactive<AddDevType.Form>({
      devTypeName: '',
      devTypeDesc: '',
      devTypeBaseDataList: [],
      devTypeConConfigSign: {
        devTypeCCId: -1,
        devTypeId: -1,
        devTypeHeart: '',
        devTypeTxTypeCode: '0018',
        devTypeDataTypeCode: '0019',
        txConf: {
          confId: -1,
          devTypeId: -1,
          jdtParamConfDesc: '',
          jdtParamConfFlag: '1',
          paramConfDataList: [],
          sort: '0'
        }
      },
      devTypeFunSign: {},
      devTypeProductFileList: []
    })

    watch(
      () => data_source,
      n => {
        console.log('form表单数据变化', data_source)
      },
      {
        deep: true
      }
    )

    watch(
      () => props.devTypeConConfigSign,
      n => {
        if (n) {
          data_source.devTypeConConfigSign = n
        } else {
          data_source.devTypeConConfigSign = {
            devTypeCCId: -1,
            devTypeId: -1,
            devTypeHeart: '',
            devTypeTxTypeCode: '0018',
            devTypeDataTypeCode: '0019',
            txConf: {
              confId: -1,
              devTypeId: -1,
              jdtParamConfDesc: '',
              jdtParamConfFlag: '1',
              paramConfDataList: [],
              sort: '1'
            }
          }
        }
      },
      { immediate: true }
    )

    const handleFormSubmit = () => {
      let data = deepClone(data_source) as AddDevType.Form

      if (Array.isArray(data.devTypeConConfigSign.txConf)) {
        data.devTypeConConfigSign.txConf.forEach((item, idx) => {
          item.sort = `${idx}`
          item.paramConfDataList.forEach((item2, idx2) => (item2.sort = `${idx2}`))
        })
      } else {
        data.devTypeConConfigSign.txConf.paramConfDataList.forEach(
          (item, idx) => (item.sort = `${idx}`)
        )
      }

      console.log('增加设备类型表单提交', data)

      emit('submit', data)
    }

    const handleFormReset = () => {
      formRef.value?.resetFields()
      location.reload()
    }

    onMounted(() => {})

    return () => (
      <div class='h-full flex flex-col bg-main'>
        <a-form
          class='overflow-auto relative h-full'
          v-model={[formRef, 'ref']}
          model={data_source}
          onFinish={handleFormSubmit}
          onFinishFailed={(error: any) => {
            console.log(error)
          }}
        >
          <div class='h-full overflow-y-auto flex flex-col gap-y-8 pt-12 px-16 pb-52'>
            {props.showFirst ? (
              <DeviceBaseInfoCard
                v-models={[
                  [data_source.devTypeName, 'name'],
                  [data_source.devTypeDesc, 'desc']
                ]}
                title={props.firstTitle}
              ></DeviceBaseInfoCard>
            ) : null}

            {props.showSecond ? (
              <DeviceBaseDatasCard
                v-model={[data_source.devTypeBaseDataList, 'baseDatas']}
                title={props.secondTitle}
              ></DeviceBaseDatasCard>
            ) : null}

            {props.showThird ? (
              <DeviceFunSignsCard
                v-model={[data_source.devTypeFunSign, 'value']}
                title={props.thirdTitle}
              ></DeviceFunSignsCard>
            ) : null}

            {props.showFourth ? (
              <DeviceConConfigCard
                v-models={[
                  [data_source.devTypeConConfigSign.devTypeTxTypeCode, 'txType'],
                  [data_source.devTypeConConfigSign.devTypeHeart, 'heart'],
                  [data_source.devTypeConConfigSign.devTypeDataTypeCode, 'dataType'],
                  [data_source.devTypeConConfigSign.txConf, 'txConf']
                ]}
                title={props.fourthTitle}
              ></DeviceConConfigCard>
            ) : null}

            {/* {props.showFifth ? (
              <DeviceTxConfigCard
                v-models={[
                  [data_source.devTypeConConfigSign.devTypeDataTypeCode, 'value'],
                  [data_source.devTypeConConfigSign.txConf, 'txConf']
                ]}
                title={props.fifthTitle}
              ></DeviceTxConfigCard>
            ) : null} */}

            {props.showSixth ? (
              <DeviceProductsCard
                value={data_source.devTypeProductFileList}
                onFileChange={val => {
                  data_source.devTypeProductFileList = val
                }}
                title={props.sixthTitle}
              ></DeviceProductsCard>
            ) : null}
          </div>
          <div class='h-mainViewfooter m-0 px-4 border-default absolute bottom-0 left-0 w-full border-t bg-white flex justify-center items-center'>
            <a-button onClick={handleFormReset}>重置表单</a-button>
            <a-button class='ml-4 ' type='primary' html-type='submit' loading={loading.value}>
              提交
            </a-button>
          </div>
        </a-form>
      </div>
    )
  }
})

export default DeviceConfigInfo
